<template>
  <el-dialog
    v-model="state.show"
    :title="state.dailogTitle"
    width="530px"
    modal-class="docDetailCreate-dailog"
  >
    <div style="height: 100%">
      <el-form
        ref="addFormRef"
        :model="state.addForm"
        label-suffix=":"
        label-width="90px"
        :rules="state.rules"
        :show-message="false"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="委托单号" prop="consignmentNo">
              <el-input
                v-model="state.addForm.consignmentNo"
                placeholder="不同委托单号请用英文,隔开"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="委托单位" prop="requester">
              <selectDown
                v-model="state.addForm.requester"
                placeholder="请输入后搜索"
                urlType="crcontactcompany"
                urlQueryData="委托单位"
                fit-input-width
                @getOption="setRequeterCode"
                :labelSpaceBetween="true"
                :remoteShowSuffix="false"
              >
              </selectDown>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="业务模式" class="table-header">
              <div style="display: flex; width: 100%">
                <el-select
                  v-model="state.seaFreightExport"
                  placeholder="请选择"
                  style="width: 40%"
                  clearable
                  filterable
                  disabled
                >
                  <el-option label="海运出口" value="海运出口"> </el-option>
                </el-select>
                <el-form-item
                  label=""
                  label-width="0"
                  prop="fclLcl"
                  style="width: 60%; margin-left: 8px; margin-bottom: 0px"
                >
                  <el-select
                    v-model="state.addForm.fclLcl"
                    placeholder="托运类型"
                    clearable
                    filterable
                  >
                    <el-option label="整箱" value="整箱"> </el-option>
                    <el-option label="拼箱" value="拼箱"> </el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="起运港" prop="loadingPort">
              <selectDown
                v-model:modelData="state.addForm.loadingPort"
                placeholder="请输入后搜索"
                urlType="port"
                @getOption="setLoadingPortCode"
                fit-input-width
                :remoteShowSuffix="false"
              >
              </selectDown>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="目的港" prop="dischargePort">
              <selectDown
                v-model:modelData="state.addForm.dischargePort"
                placeholder="请输入后搜索"
                urlType="port"
                @getOption="setDischargePortCode"
                fit-input-width
                :remoteShowSuffix="false"
              >
              </selectDown>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务类型" prop="seviceType">
              <el-checkbox-group v-model="state.addForm.seviceType">
                <el-checkbox label="订舱" :value="'订舱'" />
                <el-checkbox
                  label="拖车（集卡拖车）"
                  :value="'拖车（集卡拖车）'"
                />
                <el-checkbox
                  label="进仓（干线物流）"
                  :value="'进仓（干线物流）'"
                />
                <el-checkbox label="报关" :value="'报关'" />
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="货物类型" prop="cargoType">
              <div style="display: flex; width: 100%; align-items: center">
                <div>
                  <el-radio-group v-model="state.addForm.cargoType">
                    <el-radio :value="'普货'">普通货</el-radio>
                    <el-radio :value="'特种货'">特种货</el-radio>
                  </el-radio-group>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="箱型箱量" class="table-header">
              <el-row
                v-for="(item, index) in state.addForm.containerSums"
                :key="index"
                style="width: 100%"
              >
                <el-col :span="24">
                  <div style="display: flex; align-items: center">
                    <el-form-item
                      label=""
                      label-width="0"
                      style="width: 50%"
                      :prop="'containerSums.' + index + '.ctnType'"
                      :rules="{
                        required: true,
                        message: '请选择箱型',
                        trigger: 'change'
                      }"
                    >
                      <selectDown
                        v-model:modelData="item.ctnType"
                        placeholder="请选择"
                        urlType="csContainer"
                        fit-input-width
                        :indexOfBox="index"
                        :clearable="false"
                        @getOption="setBoxTypeTeu"
                      >
                      </selectDown>
                    </el-form-item>
                    <el-form-item
                      label=""
                      label-width="0"
                      style="margin-left: 4px; width: 50%"
                      :prop="'containerSums.' + index + '.ctnDigit'"
                      :rules="{
                        required: true,
                        message: '请输入箱量',
                        trigger: 'blur'
                      }"
                    >
                      <el-input-number
                        v-model="item.ctnDigit"
                        placeholder="请输入"
                        :precision="0"
                        :min="1"
                      />
                    </el-form-item>
                    <el-icon
                      v-if="
                        index == state.addForm.containerSums.length - 1 &&
                        index != 0
                      "
                      @click.stop="moveTableData(item)"
                      class="delete-icon"
                      :size="12"
                      ><CircleCloseFilled
                    /></el-icon>
                  </div>
                </el-col>
              </el-row>
              <div class="flex-container">
                <div class="add-use-box-info-new" @click="addUseBoxInfo">
                  <el-icon style="font-size: 15px"><Plus /></el-icon
                  ><span class="addFont">新增</span>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div>
        <el-button type="default" @click="state.show = false">取消</el-button>
        <!-- <el-button type="primary" @click="modifySubmit">{{
          isCreate ? '下一步' : '保存'
        }}</el-button> -->
        <el-button type="primary" @click="modifySubmit">创建订舱</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineComponent, nextTick, reactive, ref } from 'vue'
import AppSearchForm from '@/components/AppSearchForm.vue'
import AppPageTable, { useTableOption } from '@/components/AppPageTable2'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import { useStore, Store } from 'vuex'
import request from '@/public/request'
import selectDown from '../newBusiness/selectDownNew.vue'
import vueBus from '@/utils/vueBus'

//判断当前打开的是否是业务列表
const props = defineProps({
  isCreate: {
    type: Boolean,
    defalut: true
  }
})

const emits = defineEmits(['refresh'])

const Router = useRouter()
const Route = useRoute()
const store = useStore()

const state = reactive({
  dailogTitle: props.isCreate ? '创建订单' : '修改',
  show: false,
  addForm: {
    id: 0,
    consignmentNo: '', //托运编号
    requester: '', //委托单位
    requesterCode: '', //委托单位code
    fclLcl: '', //托运类型
    loadingPort: '', //装货港
    dischargePort: '', //卸货港
    loadingPortCode: '', //装货港五字代码
    dischargePortCode: '', //卸货港五字代码
    bookingState: 0, //0:草拟
    cargoType: '普货', //货物类型
    containerSums: [
      {
        id: 0,
        index: 1,
        bookingId: 0,
        ctnType: '',
        teu: 1,
        ctnDigit: 1,
        isDeleted: false,
        ctnOwner: ''
      }
    ], //箱型箱量
    seviceType: [] //服务类型
  },

  seaFreightExport: '海运出口', //业务类型
  customer: [],
  customerLoading: false,
  showCheck: false,
  rules: {
    consignmentNo: [
      {
        required: true,
        message: '请输入委托单号',
        trigger: 'blur'
      }
    ],
    loadingPort: [
      {
        required: true,
        message: '请选择起运港',
        trigger: 'change'
      }
    ],
    dischargePort: [
      {
        required: true,
        message: '请选择目的港',
        trigger: 'change'
      }
    ],
    requester: [
      {
        required: true,
        message: '请选择委托单位',
        trigger: 'change'
      }
    ],
    fclLcl: [
      {
        required: true,
        message: '请选择托运类型',
        trigger: 'change'
      }
    ],
    seviceType: [
      {
        type: 'array',
        required: true,
        message: '请至少选择一个服务类型',
        trigger: 'change'
      }
    ],
    cargoType: [
      {
        required: true,
        message: '请选择货物类型',
        trigger: 'change'
      }
    ]
  }
})
const addFormRef = ref('')
// 设置委托单位的code
function setRequeterCode(item) {
  state.addForm.requesterCode = item.rigthName
}
// row：只有编辑时才会带入对应的数据
async function open(row) {
  state.show = true
  if (props.isCreate) {
    await nextTick()
    state.addForm = {
      id: 0,
      consignmentNo: '', //托运编号
      requester: '', //委托单位
      requesterCode: '', //委托单位code
      fclLcl: '', //托运类型
      loadingPort: '', //装货港
      dischargePort: '', //卸货港
      loadingPortCode: '', //装货港五字代码
      dischargePortCode: '', //卸货港五字代码
      bookingState: 0, //0:草拟
      cargoType: '普货', //货物类型
      containerSums: [
        {
          id: 0,
          index: 1,
          bookingId: 0,
          ctnType: '',
          ctnDigit: 1,
          tareWeight: 1,
          isDeleted: false,
          ctnOwner: ''
        }
      ], //箱型箱量
      seviceType: [] //服务类型
    }
    addFormRef.value.resetFields()
    // let res = await request.get('/api/bucode/doccodeSerialByCode', {
    //   code: 'SYS_BUSINESS'
    // })
    // state.addForm.doccode = res
  } else {
    state.addForm.seviceType = []
    // IsInsure 对应 保险 编辑时对服务类型对应字段进行转化
    const serviceObj = {
      isNeedTrailer: '拖车',
      isToWarehouse: '进仓',
      isToCustoms: '报关',
      isInsure: '保险',
      isBooking: '订舱'
    }
    // 填充对应的信息
    state.addForm.id = row.id
    state.addForm.doccode = row.doccode
    state.addForm.requester = row.requester
    state.addForm.requesterCode = row.requesterCode
    state.addForm.bookingState = row.bookingState
    state.addForm.cargoType = row.cargoType
    state.addForm.fclLcl = row.fclLcl
    let serviceObjKeys = Object.keys(serviceObj)
    for (const item of serviceObjKeys) {
      if (row[item]) {
        state.addForm.seviceType.push(serviceObj[item])
      }
    }
  }
}

//服务类型各字段相互转化
function fieldConversion() {
  let addForm = JSON.parse(JSON.stringify(state.addForm))
  //将服务类型勾选的对应的类型字段设置为true
  addForm.IsNeedTrailer = false
  addForm.IsToWarehouse = false
  addForm.IsToCustoms = false
  addForm.IsBooking = false
  for (const iterator of addForm.seviceType) {
    switch (iterator) {
      case '订舱':
        addForm.IsBooking = true
        break
      case '拖车（集卡拖车）':
        addForm.IsNeedTrailer = true
        break
      case '进仓（干线物流）':
        addForm.IsToWarehouse = true
        break
      case '报关':
        addForm.IsToCustoms = true
        break
    }
  }
  delete addForm.seviceType
  return addForm
}

// 移除箱子
function moveTableData(row) {
  let newArr = state.addForm.containerSums.filter(
    (item) => item.index != row.index
  )
  state.addForm.containerSums = newArr
}

/**
 * 将option.rigthName
 * @param {object} item - 卸货港下拉选择的option
 */
function setDischargePortCode(item) {
  state.addForm.dischargePortCode = item.rigthName
}

/**
 * 将option.rigthName
 * @param {object} item - 卸货港下拉选择的option
 */
function setLoadingPortCode(item) {
  state.addForm.loadingPortCode = item.rigthName
}

function setBoxTypeTeu(data, index) {
  state.addForm.containerSums[index].tareWeight = data.teu ? data.teu : 1
}

/**
 * 添加用箱信息按钮点击事件
 */
async function addUseBoxInfo() {
  state.addForm.containerSums.push({
    id: 0,
    index: state.addForm.containerSums.length + 1,
    bookingId: 0,
    ctnType: '',
    ctnDigit: 1,
    tareWeight: 1,
    isDeleted: false,
    ctnOwner: ''
  })
}

// 新增或编辑
async function modifySubmit() {
  await addFormRef.value.validate()
  let req = fieldConversion()
  let api = '/api/sebooking/createBooking'
  if (!props.isCreate) {
    api = '/api/sebooking/updateBooking'
  }
  console.log(JSON.stringify(req))
  let res = await request.post(api, req)
  if (res.status) {
    ElMessage.success('成功')
    addFormRef.value.resetFields()
    if (props.isCreate) {
      Router.openTab({
        path: '/business/bussinessIndex/docWorkNewdetail',
        query: {
          id: res.data,
          title: `订舱详情`,
          establish: true,
          isJump: true
        }
      })
      emits('refresh')
    } else {
      // emits('refresh')
      vueBus.emit('refreshBussiness' + Route.query.id, '')
    }
    state.show = false
  } else {
    ElMessage.warning(res.message)
  }
}

defineExpose({
  open
})
</script>

<style lang="scss">
.docDetailCreate-dailog {
  .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
    padding: 7px 16px 7px 16px;
  }

  .el-dialog {
    padding: 0px;
  }

  .el-dialog__body {
    padding-right: 36px;
  }

  .el-dialog__footer {
    border-top: 1px solid #e8e8e8;
    text-align: center;
  }
}
</style>
<style lang="scss" scoped>
.from-container {
  border: 1px solid #e8e8e8;
  padding: 6px;
  margin-bottom: 8px;
}

.flex-container {
  display: flex;
  justify-content: flex-start;

  .add-use-box-info-new {
    color: #6ba5f6;
    cursor: pointer;
    width: 50px;
    height: 24px;
    display: flex;
    align-items: center;
    margin-left: 4px;
    flex: 0 0 50px;
    .addFont {
      margin-left: 3px;
      line-height: 24px;
    }
  }
}

.delete-icon {
  position: absolute;
  top: -5px;
  right: -4px;
  z-index: 100;
  color: #c5c5c5;
  cursor: pointer;
}

.table-header::before {
  content: '*';
  color: #f56c6c;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 12px;
  letter-spacing: 0px;
  position: absolute;
  left: 11px;
}

:deep(.el-radio) {
  margin-right: 12px;
}

:deep(.el-checkbox.el-checkbox--small) {
  margin-right: 12px;
}

:deep(.el-form-item--small .el-form-item__label) {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.85);
}

:deep(.el-form--inline .el-form-item) {
  display: flex;
  margin-right: 0;
}
:deep(.el-form-item.is-error .el-checkbox__input .el-checkbox__inner) {
  border-color: #f56c6c;
}

:deep(.el-form-item--small.el-form-item) {
  margin-bottom: 10px;
}
:deep(.el-input-number--small) {
  width: 100%;
}

:deep(.el-form--inline .el-form-item) {
  display: flex;
}
.table-header::before {
  content: '*';
  color: #f56c6c;
  font-family: PingFang SC;
  font-weight: 400;
  font-size: 12px;
  letter-spacing: 0px;
  position: absolute;
  left: 17px;
}
</style>
